import axios from 'axios'
import qs from 'qs'
import { showLoadingToast, showDialog } from 'vant'
import store from '../stores'

const http = axios.create({
  timeout: 1000 * 60,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
})

let toastInstance = null

const getConfigHeaders = () => {
  return {
    token: store.user.getToken()
  }
}

/**
 * 请求拦截
 */
http.interceptors.request.use(
  (config) => {
    if (config.showLoading) {
      toastInstance = showLoadingToast({
        message: 'Loading',
        forbidClick: true,
        duration: 0
      })
    }

    config.headers = {
      ...config.headers,
      ...getConfigHeaders()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    const _data = response.data
    if (response.request.responseType === 'blob') {
      return Promise.resolve(_data)
    }
    if (toastInstance) {
      toastInstance.close()
    }
    if (_data && _data.success === false) {
      if (_data.resultCode === 'common_0001') {
        showDialog({
          title: '提示',
          message: _data.errorMessage,
          confirmButtonColor: '#29a337'
        }).then(() => {
          const path = import.meta.env.VITE_BASE_PATH
          const userInfo = store.user.getUserInfo()
          store.user.clearUserInfo()
          location.href = `${location.origin}${path.endsWith('/') ? path : `${path}/`}${userInfo.type === 'user' ? 'login' : 'aLogin'}`
        })
      } else {
        if (response.config.showMessage) {
          showDialog({
            title: '提示',
            message: _data.errorMessage,
            confirmButtonColor: '#29a337'
          })
        }
        return Promise.reject(_data.errorMessage)
      }
    }

    return Promise.resolve(_data.module)
  },
  (error) => {
    if (toastInstance) {
      toastInstance.close()
    }
    showDialog({
      title: '提示',
      message: `服务器错误，请联系管理员.${error.config.url}.${error.message}`,
      confirmButtonColor: '#29a337'
    })
    return Promise.reject(error)
  }
)

/**
 * 请求地址处理
 * @param {*} actionName action方法名称
 */
http.adornUrl = (actionName) => {
  const userInfo = store.user.getUserInfo()
  if (!userInfo.id) {
    return `${window.location.href.endsWith('/login') ? import.meta.env.VITE_BASE_URL_USER : import.meta.env.VITE_BASE_URL_ADMIN}${actionName}`
  }
  return `${userInfo.type === 'user' ? import.meta.env.VITE_BASE_URL_USER : import.meta.env.VITE_BASE_URL_ADMIN}${actionName}`
}

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
http.adornParams = (params = {}, openDefultParams = true) => {
  let defaults = {}
  return openDefultParams ? Object.assign({}, defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
http.adornData = (data = {}, contentType = 'json') => {
  if (contentType === 'form') {
    http.defaults.headers['Content-Type'] = 'multipart/form-data'
    return data
  }
  return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

http.getFileBlob = async (url, params = {}) => {
  try {
    const blob = await http.post(url, params, {
      transformRequest: [
        (params_1) => {
          let result = ''
          Object.keys(params_1).forEach((key) => {
            if (!Object.is(params_1[key], undefined) && !Object.is(params_1[key], null)) {
              result += encodeURIComponent(key) + '=' + encodeURIComponent(params_1[key]) + '&'
            }
          })
          return result
        }
      ],
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    return blob
  } catch (r) {
    console.error(r, '-------------------++++')
    showDialog({
      title: '提示',
      message: '预览失败',
      confirmButtonColor: '#29a337'
    })
  }
}

export default http
